package com.example.servlet.feature;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class JavaNewFeature {

    // 模式匹配
    public void patternMatching() {
        Map<String, Object> data = new HashMap<>();
        data.put("key", "aaa");
        var obj = data.get("key");

        // Switch的模式匹配
        var result = switch (obj) {
            case Integer i -> i; // 如果 obj 是 Integer 类型，则执行此代码块
            case String s -> s.length(); // 如果 obj 是 String 类型，则执行此代码块
            default -> throw new IllegalArgumentException("Invalid input");
        };
    }

    // 虚拟线程
    public void virtualThread() {
        Runnable runnable = () -> {
            System.out.println("Hello, World");
        };

        // 可以指定虚拟线程的名字
        ThreadFactory virtualThreadFactory = Thread.ofVirtual()
                .name("java", 0)
                .factory();

        Thread factoryThread = virtualThreadFactory.newThread(runnable);
        factoryThread.start();

        // 建议使用虚拟线程执行器，代码如下，
        try (ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 100; i++) {
                executorService.submit(runnable);
            }
        }
    }

    // 有序集合
    public void orderedCollection() {
        // 有序集合
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(3);
        list.add(2);
        System.out.println("Before sorting: " + list);
        list.addFirst(5);
        list.addLast(4);
        System.out.println("After sorting: " + list);
        list.sort(Comparator.comparingInt(a -> a));
        System.out.println("After sorting with comparator: " + list);
        list.reversed();
        System.out.println("After reversing: " + list);
        list.removeFirst();
        list.removeLast();
        System.out.println("After removing first and last: " + list);
    }

}
